/**
 * Project Name:fastPlat
 * File Name:MdDataController.java
 * Package Name:com.fast.cms.web.controller.article
 * Date:2018年08月26日 09时59分43秒
 * Copyright (c) 2018, lsflu@126.com All Rights Reserved.
 *
*/

package com.fast.cms.web.controller.article;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fast.base.cache.MemcachedUtils;
import com.fast.base.db.page.PageView;
import com.fast.base.model.AnoSysLog;
import com.fast.base.util.DateUtils;
import com.fast.base.util.LogUtils;
import com.fast.base.util.StringUtils;
import com.fast.base.util.web.ResponseData;
import com.fast.base.util.web.ResponseEnum;
import com.fast.base.web.BaseController;
import com.fast.cms.model.article.BatchDataInfo;
import com.fast.cms.model.article.MdData;
import com.fast.cms.service.article.MdDataService;
import com.fast.cms.service.system.SysLogService;
import com.fast.cms.web.form.BatchDataInfoListForm;
import com.fast.cms.web.form.MdDataForm;
import com.fast.common.CacheConstant;
import com.fast.common.userCache.AdminCacheUtils;
import com.fast.common.userCache.UserRequestUtils;
import com.fast.user.model.admin.AdminUser;
import com.fast.user.model.admin.SysLog;

/**
 * ClassName:MdDataController <br/>
 * 用途: MdData web控制类 <br/>
 * 开发人员：lushuifa  http://lushuifa.iteye.com/
 * 邮箱:lsflu@126.com
 * @version  1.0
 * @since    JDK 1.6
 * @see
 * Date:     2018年08月26日 09时59分43秒 <br/> 	 
 */
@Controller
@RequestMapping("/mdData")
public class MdDataController extends BaseController{
	
	private Log log = LogFactory.getLog(MdDataController.class);
	
	@Resource(name="mdDataService")
	private MdDataService mdDataService;
	
	@Resource(name="sysLogService")
	protected SysLogService logS;
	
	/**
	 * 说明:去重检查 <br>
	 * 编写者:lushuifa
	 * 创建时间:2018年9月16日 下午5:01:48 </pre>
	 * @param 
	 * @return ResponseData 说明
	 */
	@ResponseBody
	@RequestMapping("/checkReaptDataFile.do")
	public ResponseData checkReaptDataFile(@RequestParam MultipartFile impFile){
		ResponseData responseData = new ResponseData();
		//再导入详情信息
		String strDirPath = super.getRequest().getSession().getServletContext().getRealPath("/");
		String savePath = strDirPath + "/excel/";
		String fileDiskPath = "";
		try {
			if (!impFile.isEmpty()) {
				String fileName = "checkReaptDataFile.txt";
				fileDiskPath = savePath + fileName;
				impFile.transferTo(new File(fileDiskPath));
			}
			String checkMsg = this.mdDataService.checkReaptDataFile(fileDiskPath);
			if (StringUtils.isBlank(checkMsg)) {
				responseData.success();
				responseData.setData(checkMsg);
			} else {
				responseData.failue();
				responseData.setMsg(checkMsg);
			}
		} catch (IOException e1) {
			responseData.failue();
			LogUtils.error("importDataFromXls error:", e1);
		}
		return responseData;
	}
	
	/**
	 * 说明: 导入数据 <br>
	 * 编写者:lushuifa
	 * 创建时间:2018年8月26日 上午10:12:06 </pre>
	 * @param 
	 * @return ResponseData 说明
	 */
	@ResponseBody
	@RequestMapping("/importDataFromTxt.do")
	public ResponseData importDataFromTxt(@RequestParam MultipartFile impFile,String dataType){
		ResponseData responseData = new ResponseData();
		//再导入详情信息
		String strDirPath = super.getRequest().getSession().getServletContext().getRealPath("/");
		String savePath = strDirPath + "/excel/";
		String fileDiskPath = "";
		try {
			if (!impFile.isEmpty()) {
				String fileName = "importDataFromTxt.txt";
				fileDiskPath = savePath + fileName;
				impFile.transferTo(new File(fileDiskPath));
			}
			AdminUser adminUser = AdminCacheUtils.getLoginAdminUser();
			String key = CacheConstant.getLockKey("importDataFromTxt");
			if (MemcachedUtils.getCachedClient().keyExists(key)) {
				responseData.failue();
				String realName =  (String) MemcachedUtils.get(key);
				responseData.setMsg("用户【"+realName+"】上传的数据还在后台运行，请你晚点再操作！");
				return responseData;
			}else {
				MemcachedUtils.set(key , adminUser.getRealName(),60*15);
				String impData = this.mdDataService.batchSaveMdDataByImpFile(fileDiskPath,dataType,adminUser);
				MemcachedUtils.delete(key);
				if (StringUtils.isNotBlank(impData)) {
					responseData.success();
					responseData.setData(impData);
				} else {
					responseData.failue();
					responseData.setMsg("导入失败请检查一下你的内容！");
				}
			}
		} catch (IOException e1) {
			responseData.failue();
			LogUtils.error("importDataFromXls error:", e1);
		}
		return responseData;
	}

	/**
	 * 编辑MdData信息
	 * @param imageUrl
	 * @return
	 */
	@RequestMapping("/editMdData.do")
	@ResponseBody
	@AnoSysLog(actionName="编辑MdData信息")
	public ResponseData editMdData(){
		ResponseData responseData = new ResponseData();
		MdData mdData = null;
		try {
			int id = webUtil.getInt("id");
			if(id>0){
				mdData = this.mdDataService.getById(MdData.class,id);
				mdData = (MdData) webUtil.bindDataToBean(mdData);
			}else{
				mdData = new MdData();
				mdData = (MdData) webUtil.bindDataToBean(mdData);
				UserRequestUtils.bindCreaterInfo(mdData);
			}
			UserRequestUtils.bindEditorInfo(mdData);
			MdData resultBean = this.mdDataService.merge(mdData);
			if(resultBean!=null){
				if (resultBean.getValidateFlag()==0) {
					this.mdDataService.fileterPingPaiGanCi(mdData.getUuid(), mdData.getDataTitle());
					this.mdDataService.fileterTitleGanCi(mdData.getUuid(), mdData.getDataTitle());
					this.mdDataService.supplementBatchData();
				}
			    responseData.setData(resultBean);
				responseData.buildResult(ResponseEnum.EDIT_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.EDIT_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 删除MdData信息到回收站
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delMdDataByIdForHS.do")
	@AnoSysLog(actionName="删除MdData到回收站")
	public ResponseData delMdDataByIdForHS(int id) {
		log.info("delMdDataByIdForHS id=:"+id);
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = mdDataService.deleteByIdForHS(MdData.class, id);
			if(actionFlag){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		log.info("delMdDataByIdForHS responseData=:"+responseData.toString());
		return responseData;
	}

	/**
	 * 删除MdData信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delMdDataById.do")
	@AnoSysLog(actionName="彻底删除MdData")
	public ResponseData delMdDataById(int id) {
		log.info("delMdDataById id=:"+id);
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = mdDataService.deleteById(MdData.class, id);
			responseData.setCode(actionFlag?"00":"01");
			if(actionFlag){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		log.info("delMdDataById responseData=:"+responseData.toString());
		return responseData;
	}
	
	/**
	 * 删除多个MdData信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/batchDelMdData.do")
	@AnoSysLog(actionName="批量删除MdData信息")
	public ResponseData batchDelMdData(String ids){
		ResponseData responseData = new ResponseData();
		try {
			int actionCount = mdDataService.deleteByIds(MdData.class, ids);
			if(actionCount>0){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 删除多个MdData信息到回收站
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/batchDelMdDataForHS.do")
	@AnoSysLog(actionName="批量删除MdData")
	public ResponseData batchDelMdDataForHS(String ids){
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = mdDataService.batchDeleteByIdsForHS(MdData.class, ids);
			if(actionFlag){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 分页得到MdData列表
	 * @return PageView<MdData>
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping("/getMdDataList.do")
	public Object getMdDataList(MdDataForm mdDataForm){
		log.info("getMdDataList param:"+mdDataForm.toString());
		Map<String,Object> gridMap = new HashMap<String,Object>();
		PageView<MdData> pageView = null;
		try {
			pageView = this.mdDataService.getMdDataList(mdDataForm);
			gridMap.put("total", pageView.getTotalRecord());
			gridMap.put("rows", pageView.getRecords());
		} catch (Exception e) {
			log.error("getMdDataList err:",e);
		}
		log.info("getMdDataList result:"+pageView.toString());
 		return gridMap;
	}
	
	/**
	 * 说明: 敏感词列表 <br>
	 * 编写者:lushuifa
	 * 创建时间:2018年9月4日 下午11:44:26 </pre>
	 * @param 
	 * @return Object 说明
	 */
	@ResponseBody
	@RequestMapping("/getMianGanList.do")
	public Object getMianGanList(){
		log.info("getMianGanList param ");
		Map<String,Object> gridMap = new HashMap<String,Object>();
		PageView<Map<String, Object>> pageView = null;
		try {
			pageView = this.mdDataService.getMianGanList();
			gridMap.put("total", pageView.getTotalRecord());
			gridMap.put("rows", pageView.getRecords());
		} catch (Exception e) {
			log.error("getMianGanList err:",e);
		}
		log.info("getMianGanList result:"+pageView.toString());
 		return gridMap;
	}
	
	/**
	 * 说明: 删除敏感词 <br>
	 * 编写者:lushuifa
	 * 创建时间:2018年9月4日 下午11:53:41 </pre>
	 * @param 
	 * @return Object 说明
	 */
	@ResponseBody
	@RequestMapping("/deleteCihui.do")
	public Object deleteCihui(String mianganCi){
		ResponseData responseData = new ResponseData();
		try {
			int actionCount = mdDataService.deleteCihui(mianganCi);
			if(actionCount>0){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	@ResponseBody
	@RequestMapping("/batchDeleteCihui.do")
	public Object batchDeleteCihui(String mianganciArray){
		ResponseData responseData = new ResponseData();
		try {
			int actionCount = mdDataService.batchDeleteCihui(mianganciArray);
			if(actionCount>0){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	
	/**
	 * 清除数据
	 * 编写者:lushuifa
	 * 创建时间:2018年9月14日 下午11:43:08 </pre>
	 * @param 
	 * @return Object 说明
	 */
	@ResponseBody
	@RequestMapping("/clearData.do")
	public Object clearData(){
		ResponseData responseData = new ResponseData();
		try {
			boolean flag = mdDataService.clearTable(MdData.class);
			boolean flag2 = mdDataService.clearTable(BatchDataInfo.class);
			if(flag&&flag2){
				responseData.buildResult(ResponseEnum.DELETE_SUCCESS);
			}else{
				responseData.buildResult(ResponseEnum.DELETE_FAILUE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.failue();
		}
		return responseData;
	}
	
	
	/**
	 * 说明: 获取批次列表  <br>
	 * 编写者:lushuifa
	 * 创建时间:2018年8月26日 下午5:24:22 </pre>
	 * @param 
	 * @return Object 说明
	 */
	@ResponseBody
	@RequestMapping("/getBatchDataInfoList.do")
	public Object getBatchDataInfoList(BatchDataInfoListForm batchDataInfoListForm){
		log.info("getBatchDataInfoList param:"+batchDataInfoListForm);
		Map<String,Object> gridMap = new HashMap<String,Object>();
		PageView<BatchDataInfo> pageView = null;
		try {
			pageView = this.mdDataService.getBatchDataInfoList(batchDataInfoListForm);
			gridMap.put("total", pageView.getTotalRecord());
			gridMap.put("rows", pageView.getRecords());
		} catch (Exception e) {
			log.error("getBatchDataInfoList err:",e);
		}
		log.info("getBatchDataInfoList result:"+pageView.toString());
 		return gridMap;
	}
	
	/**
	 * 获取MdData详情
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/js/getMdDataDetail.do")
	public ResponseData getAjaxMdDataDetail(int id) {
		log.info("getMdDataDetail is comming:id="+id);
		ResponseData responseData = new ResponseData();
		try {
			MdData mdData = mdDataService.queryForBeanById(MdData.class, id);
			String dataTitle = mdData.getDataTitle();
			String titleGanCi = mdData.getTitleGanCi();
        	if(StringUtils.isNotBlank(titleGanCi)){
            	String[] titleGanCiArray = titleGanCi.split(",");
            	for (int i = 0; i < titleGanCiArray.length; i++) {
            		dataTitle =  dataTitle.replaceAll(titleGanCiArray[i],"<font color=red><b>"+titleGanCiArray[i]+"</b></font>");
				}
        	}
        	
        	String pingpaiGanCi = mdData.getPingpaiGanCi();
        	if(StringUtils.isNotBlank(pingpaiGanCi)){
            	String[] pingpaiGanCiArray = pingpaiGanCi.split(",");
            	for (int i = 0; i < pingpaiGanCiArray.length; i++) {
            		dataTitle = dataTitle.replaceAll(pingpaiGanCiArray[i],"<font color=red><b>"+pingpaiGanCiArray[i]+"</b></font>");
				}
        	}
        	mdData.setDataTitleVmg(dataTitle);
			responseData.setData(mdData);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("获取MdData详情getMdDataDetail err",e);
			responseData.failue();
		}
		return responseData;
	}
	
	/**
	 * 说明: 获取批次的详情信息 <br>
	 * 编写者:lushuifa
	 * 创建时间:2018年9月9日 下午6:09:35 </pre>
	 * @param 
	 * @return ResponseData 说明
	 */
	@ResponseBody
	@RequestMapping("/mdData/js/getBatchInfoDetail.do")
	public ResponseData getBatchInfoDetail(int id) {
		log.info("getMdDataDetail is comming:id="+id);
		ResponseData responseData = new ResponseData();
		try {
			MdData mdData = mdDataService.queryForBeanById(MdData.class, id);
			responseData.setData(mdData);
		} catch (Exception e) {
			e.printStackTrace();
			log.info("获取MdData详情getMdDataDetail err",e);
			responseData.failue();
		}
		return responseData;
	}
	
	
	
	/**
	 * 查询MdData详情
	 * @param id
	 * @return
	 */
	@RequestMapping("/getMdDataDetail.do")
	public ModelAndView getMdDataDetail(int id,String actionType) {
		ModelAndView mv = new ModelAndView();
		MdData bean = mdDataService.queryForBeanById(MdData.class, id);
		try {
			mv.addObject("mdData",bean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(StringUtils.equals(actionType,"update")){
			mv.setViewName("/adminMain/mdData/mdData-add.jsp");
		}else{
			mv.setViewName("/adminMain/mdData/mdData-detail.jsp");
		}
		return mv;
	}
	
	/**
	 * 说明: 下载文件 <br>
	 * 编写者:lushuifa
	 * 创建时间:2018年8月27日 下午11:20:03 </pre>
	 * @param 
	 * @return ModelAndView 说明
	 */
	@RequestMapping("/downloadFile.do")
	public void downloadFile(String uuid,HttpServletResponse response) {
		try {
			String batchNo = uuid;
			String fileDiskPath = super.getFileDiskPath();
			String imgApp = super.getImgPath();
			byte[] data = this.mdDataService.downloadFile(batchNo,fileDiskPath,imgApp);
		    String fileName = "batch_"+uuid+".txt";  
		    
		    //添加下载记录
			AdminUser adminUser = AdminCacheUtils.getLoginAdminUser();
	        SysLog sysLog = new SysLog();
	        sysLog.setActionName(fileName);
	        sysLog.setLogData("");
	        sysLog.setOperator(adminUser.getRealName());
	        sysLog.setLogDate(DateUtils.getNow());
	        sysLog.setLogType("mdData_download");
	        logS.persist(sysLog);
	        
		    response.reset();  
		    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
		    response.addHeader("Content-Length", "" + data.length);  
		    response.setContentType("application/octet-stream;charset=UTF-8");  
		    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
		    outputStream.write(data);  
		    outputStream.flush();  
		    outputStream.close();  
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

